"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var express = require('express');
var router = express.Router();
const path = require("path");
var _ = require('@qianmi/x-site-common/util/response-util');
var { envCode } = require('../config');
var { ossClient } = require('../service/load-update-service');
var fse = require('fs-extra');
var ejs = require('ejs');
var fs = require('fs');
const initService = require("../service/init-service");
let publishLogService = require('../mongoose/service/publish-log-service');
let versionHistoryService = require('../mongoose/service/version-history-service');
/**
 * 获取部署日志
 */
router.all('/getLogs', function (req, res, next) {
    (async () => {
        let envCode = req.body.envCode;
        let projectName = req.body.projectName;
        let pageSize = req.body.pageSize;
        let pageNum = req.body.pageNum;
        let result = await publishLogService.getPublishLogs({ envCode, projectName, pageSize, pageNum });
        res.status(200).send(_.resultSucess(result));
    })();
});
/**
 * 保存开发者打版本记录
 */
router.all('/saveLocalPublish', function (req, res, next) {
    (async () => {
        let name = req.body.name;
        let version = req.body.version;
        let username = req.body.username;
        let email = req.body.email;
        let publishTime = req.body.publishTime;
        let branch = req.body.branch;
        let result = await versionHistoryService.addVersionHistory({ name, version, username, email, publishTime, branch });
        res.status(200).send(_.resultSucess('OK'));
    })();
});
/**
 * 获取开发者打的版本记录
 */
router.all('/getVersionHistories', function (req, res, next) {
    (async () => {
        let name = req.body.name;
        let pageSize = req.body.pageSize;
        let pageNum = req.body.pageNum;
        let result = await versionHistoryService.getHistories({ name, pageNum, pageSize });
        res.status(200).send(_.resultSucess(result));
    })();
});
/**
 *
 * http://oss-hz.qianmi.com /x-site/developer/resources
 * 部署开发者静态资源, 如图片,JS CSS等文件 到阿里云
 * 路径为
 */
router.all('/upload', function (req, res, next) {
    try {
        _uploadFile({
            uploadPath: req.body.uploadPath,
            fileContents: req.body.fileContents
        }).then((response) => {
            res.send('//qianmi-web.oss-cn-hangzhou.aliyuncs.com' + response.name);
        }, err => {
            console.warn(err);
            res.status(500);
        });
    }
    catch (err) {
        res.end('error');
    }
});
/**
 *
 * /resources/getXSiteResource
 */
router.all('/getXSiteResource', function (req, res, next) {
    _dealBus(req, res);
});
/**
 *  platForm  pc wei xin
 *  type  index inner
 *
 */
router.all('/:platForm/:type/editor/html', function (req, res, next) {
    let platForm = req.params.platForm, type = req.params.type;
    readFileContent(req, res, { platForm, type });
});
router.all('/:platForm/templateIndex', function (req, res, next) {
    //从阿里云加载. 最新的.
    let platForm = req.params.platForm;
    ossClient.getObjectAbsolute('/x-site/prod/public/template-index/' + platForm + '-template-index.json')
        .then(content => {
        res.end(content.content.toString());
    }, err => {
        res.end();
        console.log(err);
    });
});
router.all('/eslint/:fileName', function (req, res, next) {
    let fileName = req.params.fileName;
    (async () => {
        let filePath;
        if (fileName === 'editorCf') {
            filePath = path.join(__dirname, '../.editorconfig');
        }
        else if (fileName === 'ignore') {
            filePath = path.join(__dirname, '../.eslintignore');
        }
        else {
            filePath = path.join(__dirname, '../.eslintrc.js');
        }
        let content = await _readFile(filePath);
        res.end(content);
    })();
});
let userData = {
    xsiteEnvironment: "test",
    envCode: 'test',
    systemCode: 'd2cStore',
    systemCodeZip: 'd2cStore',
    initConfig: {
        platForm: "",
        pageType: "",
        pageCode: "",
        usrId: "A1078241",
        nickName: "qmtest001",
        configOrderStr: "",
        globalSetup: "eJzVWU1v20YQ/S/sVbT2+8NA0RbNxUAOReO7seQuZcKUqIhUbNfwoQgSFG2BBGiDXloUCdrAPSVFE7RFgfwbOc6/6FCkRMqSJcVNnPRiwcvh7ryZ2TdvuUfebprl3uaR1w+9TW83z/ub7XaWpwPHicQSbwQk3MAIoY0w7Xotb9/FB3GvNu319vb2kiTZ2LdTs/YnGElFGAZ70493yiUmb8DIhoVJb8am143H0x63vCzOXdf0TMcNCm+si8wwmTp25GEmFdJMCS4UHQ+D6Y38MHEwc1b87gSpPUSwZPFk+7BfPOjDyjBhy9t1xl6/5W3Slpf3ky0Lz4Q21BKLfW4j42PshB8YTH0WaI0EU8pRCW9mucmHWTHXMEjibNdZGBz2rcnddtyFRSaeSSYpg+njfOwToad//Xb68/dgHaVpXi1e+PZpaguDWURjv6onXTPY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4qHvFmZdD5uqihLQ7FFSky40AwXJEiowr9V0W2fzAn0zFGaplMV5eOjkE0YAw0FidRdbQ0EaM+xwx4kzgHJPomolOAADZufjGhoBoWCvgK7bLgTOgUc8WkEFypNRnkbdIGJwTBMYWThnZ69fD5q58elQpqQS00/F+LLRhBCItCnl0V3l6aL5OLhT8AnNPzTFlCRuPPPefEYo1hLcxANNCGMKPo/eoSpV9KsRm1QJd/oWiAWQu81AiaugBu+R/vfqkxovBLZePMd+/b0d9/jO49JXMF0sC8DgcwELuIEoz4e7InCn8EIc0PV5V6ePB4fjfU3q+pFxBBTGu85JPVCr3gVOjC0I31AqmyDsc3UMxCSm4Dg5ybyfpiwfBazRERQRSXjQJIF+iFKbSL9MLxcXV3sF3NUt4qAKF45fgWRGur27kxaFxvpFnm737RuIBol6fldn+Q2jbMe6O4/2gPMzf4HPbttXgwvdFox11wMWt3Ld/o9zofRYnpfDhuUxx4W5ZtqnGX0aouMlr9sDX9aty64BvzpKCnH7rHNx9J2klr3+Nup75nudn1jQ8jpeMTF5VByODAclTc4UTEQlohkJIFQqswEIXjH2PF93cE2t3B+7vFQBHKfwGr5vsb",
        id: "" //这个是模板ID 正常情况通过URL获取到..
    },
    serviceConfig: {
        image_server: "",
        admin_main: "",
    },
    systemConfig: '{}',
    bundleMap: {},
    filename: "",
    userId: "A1078241",
    commonUrls: {},
    HashCodes: {
        "index.css": 1,
        "indexNew.css": 1,
        "base.css": 1,
        "jquery-ui.css": 1,
    },
    jwtToken: "",
    siteAnalysis: [],
};
async function readFileContent(req, res, { platForm, type }) {
    let bundleMap = await initService.getXSiteJsCssRel();
    res.set('Content-Type', 'text/html');
    userData.bundleMap = bundleMap;
    userData.systemConfig = JSON.stringify(require('../temp/@qianmi/x-site/interface').default['d2cStore']);
    try {
        if (platForm === 'pc' && type === 'index') {
            let _filePath = path.join(__dirname, '../temp/@qianmi/x-site/views/prototype.html');
            let _templateContent = await _readFile(_filePath);
            let result = Object.assign({}, userData);
            result.initConfig.platForm = 'pc';
            result.initConfig.pageType = 'index';
            result.initConfig.pageCode = 'index';
            result.filename = _filePath;
            res.end(_dealHtml(ejs.render(_templateContent, result)));
        }
        else if (platForm === 'pc' && type === 'inner') {
            let _filePath = path.join(__dirname, '../temp/@qianmi/x-site/views/pcInner.html');
            let _templateContent = await _readFile(_filePath);
            let result = Object.assign({}, userData);
            result.initConfig.platForm = 'pc';
            result.initConfig.pageType = 'inner';
            result.initConfig.pageCode = 'inner';
            result.filename = _filePath;
            res.end(_dealHtml(ejs.render(_templateContent, result)));
        }
        else if (platForm === 'weixin' && type === 'index') {
            let _filePath = path.join(__dirname, '../temp/@qianmi/x-site/views/weixin.html');
            let _templateContent = await _readFile(_filePath);
            let result = Object.assign({}, userData);
            result.initConfig.platForm = 'weixin';
            result.initConfig.pageType = 'index';
            result.initConfig.pageCode = 'index';
            result.filename = _filePath;
            res.end(_dealHtml(ejs.render(_templateContent, result)));
        }
        else if (platForm === 'weixin' && type === 'inner') {
            let _filePath = path.join(__dirname, '../temp/@qianmi/x-site/views/weixin.html');
            let _templateContent = await _readFile(_filePath);
            let result = Object.assign({}, userData);
            result.initConfig.platForm = 'weixin';
            result.initConfig.pageType = 'inner';
            result.initConfig.pageCode = 'inner';
            result.filename = _filePath;
            res.end(_dealHtml(ejs.render(_templateContent, result)));
        }
    }
    catch (err) {
        console.error(err);
        res.end('err');
    }
}
function _dealHtml(htmlContent) {
    return htmlContent.replace('<script src="/javascripts/dll/vendor_weixin.dll.js"></script>', '<script src="//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/test/public/javascripts/dll/vendor_weixin.dll.js"></script>')
        .replace('<script src="/javascripts/dll/vendor_pc.dll.js"></script>', '<script src="//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/test/public/javascripts/dll/vendor_pc.dll.js"></script>')
        .replace('var config = {', 'var config = {\n isDevelopTpl:true,');
}
async function _dealBus(req, res) {
    let xSiteJSCSS = await initService.getXSiteJsCssRel();
    res.json(_.resultSucess(xSiteJSCSS));
}
/**
 * 读取文件内容;;
 * @param filePath
 * @return {Promise<T>}
 * @private
 */
function _readFile(filePath) {
    return new Promise((resolve, reject) => {
        fs.readFile(filePath, (err, data) => {
            resolve(data.toString());
        });
    });
}
let OssPrex = `/x-site/public`;
async function _uploadFile({ uploadPath, fileContents }) {
    let result = await ossClient.putObjectAbsolute(new Buffer(fileContents, 'base64'), path.join(OssPrex, uploadPath));
    return result;
}
module.exports = router;
